package com.guocheng.modules.dictionarie.init;

import com.guocheng.config.SpringUtil;
import com.guocheng.modules.dictionarie.model.Dictionarie;
import com.guocheng.modules.dictionarie.utils.Dictionaries;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class DictionariesInit {

    //查询的数据库字段名
    private String[] conlum = {"id","parent_id","name","value","type","permission"};
    //sql语句
    private String sql = "select `"+conlum[0]+"`,`"+conlum[1]+"`,`"+conlum[2]+"`,`"+conlum[3]+"`,`"+conlum[4]+"`,`"+conlum[5]+"` from sys_dictionaries where `status` = 1";

    //初始化数据字典
    public boolean initDictionaries(){
        DataSource dataSource = SpringUtil.getBean(DataSource.class);
        //加载数据字典
        Dictionaries dictionaries = new Dictionaries();
        try {
            Connection connection = dataSource.getConnection();
            Statement statement = connection.createStatement();
            //手写sql查询数据字典
            ResultSet resultSet = statement.executeQuery(sql);

            //循环每一条数据
            while (resultSet.next()) {

                String id = resultSet.getString(conlum[0]);
                String parentId = resultSet.getString(conlum[1]);
                String name = resultSet.getString(conlum[2]);
                String value = resultSet.getString(conlum[3]);
                String type = resultSet.getString(conlum[4]);
                String permission = resultSet.getString(conlum[5]);

                if(parentId.equals("0")){
                    if(dictionaries.get(type)== null) { //父字典也加载
                        dictionaries.put(type,new ArrayList<>());
                    }
                    if (dictionaries.get(value)== null)    //判断父字典是否为空
                        dictionaries.put(value,new ArrayList<>());
                }

                //加载子字典
                List<Dictionarie> dictionaries1 = dictionaries.get(type);
                Dictionarie dictionarie = new Dictionarie();
                dictionarie.setId(Integer.valueOf(id));
                dictionarie.setParentId(Integer.valueOf(parentId));
                dictionarie.setName(name);
                dictionarie.setValue(value);
                dictionarie.setPermission(permission);
                dictionaries1.add(dictionarie);
            }
            resultSet.close();
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
        //放入内存静态区域中
        Dictionaries.setDictionaries(dictionaries);
        System.gc();    //执行垃圾回收机制
        return true;
    }

}
